﻿using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using T_vehicle.Domain;
using T_vehicle.Infrastructure.Impl;

namespace T_vehicle.Infrastructure
{
    public class BaseRepository<T> : IRepository<T> where T : class
    {
        private readonly MyDbContext myDbContext;

        public BaseRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        public async Task<int> AddAsync(T t)
        {
           await myDbContext.AddAsync(t);
            var res = await myDbContext.SaveChangesAsync();
            return res;
        }

      


        public async Task<int> Delete(int id)
        {
            var info = myDbContext.Set<T>().Find(id);
            myDbContext.Remove(info);
            return await myDbContext.SaveChangesAsync();
        }



        public async Task<List<T>> GetAllAsync()
        {
            return await myDbContext.Set<T>().ToListAsync();
        }



        public async Task<T> GetAllAsync(Expression<Func<T, bool>> expre)
        {

            DbSet<T> dbSet = myDbContext.Set<T>();
            return await dbSet.FirstOrDefaultAsync(expre);
        }



        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await myDbContext.Set<T>().Where(expre).ToListAsync();
        }


        public async Task<T> GetModelAsync(int id)
        {
            return await myDbContext.Set<T>().FindAsync(id);
        }



        public async Task<int> UpdateAsync(T t)
        {
            myDbContext.Update(t);
            return await myDbContext.SaveChangesAsync();
        }


        public async Task<int> UpdateAsyncRange(List<T> info)
        {

            myDbContext.UpdateRange(info);
            return await myDbContext.SaveChangesAsync();
        }
    }
}
